package controller;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pojo.Page;
import pojo.SysRole;
import pojo.SysUser;
import service.SysRoleService;
import service.SysUserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController extends BaseController {
    private Logger logger=Logger.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    @RequestMapping(value = "/toLogin")
    public String Login(){
        logger.debug("跳转到登录页面");
        return "login";
    }
    //登录
    @RequestMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, @RequestParam String account, @RequestParam String password){
        logger.debug("进入登录方法");
        SysUser sysUser=sysUserService.login(account,password);
        if (null!=sysUser){
            //登录成功，重定向到/user/toMain接口
            session.setAttribute("userSession",sysUser);
            return "redirect:/user/toMain";
        }
        else {
            //用户不存在，登录失败，跳转到登录页面
            throw new RuntimeException("用户名或密码不正确");
        }

    }
    //跳转到首页
    @RequestMapping("/toMain")
    public String main(){
        return "frame";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }
    //查询用户列表
    @RequestMapping("/list")
    public String getUserList(Model model, String realName,Integer roleId,@RequestParam(defaultValue = "1")Integer pageIndex){
        List<SysUser> userList=null;
        List<SysRole> roleList=null;
        Page page=new Page();
        page.setPageSize(5);
        page.setCurPage(pageIndex);
        userList=sysUserService.selectUserList(realName,roleId,page);
        roleList=sysRoleService.getRoles();
        model.addAttribute("userList",userList);
        model.addAttribute("roleList",roleList);
        model.addAttribute("queryRealName",realName);
        model.addAttribute("queryRoleId",roleId);
        model.addAttribute("totalPageCount",page.getTotalPage());
        model.addAttribute("totalCount",page.getTotalCount());
        model.addAttribute("currentPageNo",page.getCurPage());
        userList.forEach(sysUser -> System.out.println(sysUser));
        return "sysUser/list";
    }
    @GetMapping("toAdd")
    public String toAdd(){
        return "sysUser/add";
    }
    @PostMapping("add")
    public String add(SysUser sysUser,HttpSession session){
        sysUser.setCreatedUserId(((SysUser)session.getAttribute("userSession")).getId());
        if (sysUserService.add(sysUser)>0){
            return "redirect:/user/list";
        }
        return "sysUser/add";


    }
    @RequestMapping("toUpdatePwd")
    public String toUpdatePwd(){
        return "sysUser/updatePassword";
    }
    @ResponseBody
    @GetMapping("checkOldPwd")
    public Object checkOldPwd(HttpSession session,@RequestParam String oldpassword){
        logger.debug("验证原密码 oldpassword"+oldpassword+"是否正确");
        HashMap<String,Object> resultMap=new HashMap<String, Object>();
        SysUser sysUser= (SysUser) session.getAttribute("userSession");
        if (sysUserService.getPwdTrue(sysUser,oldpassword)){
            resultMap.put("result","true");
        }else{
            resultMap.put("result","false");
        }
        return JSON.toJSONString(resultMap);
    }
    @PostMapping("savePassword")
    public String savePassword(HttpSession session,@RequestParam String newpassword, Model model){
        SysUser sysUser= (SysUser) session.getAttribute("userSession");
        if (sysUserService.updatePwd(sysUser,newpassword)>0){
            return "login";
        }else {
            model.addAttribute("error","修改密码错误");
        }
        return "sysUser/updatePassword";
    }
    @ResponseBody
    @GetMapping("/userExist")
    public Object userExist(@RequestParam String account){
        logger.debug("验证用户名account="+account+"的用户是否存在");
        HashMap<String,Object> resultMap=new HashMap<String, Object>();
        if (StringUtils.isNullOrEmpty(account)){
            resultMap.put("exist",1);
        }else {
            SysUser sysUser=sysUserService.getAccountExist(account);
            if (null!=sysUser){
                resultMap.put("exist",1);
            }else {
                resultMap.put("exist",0);
            }
        }
        return resultMap;
    }


    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest request){
        request.setAttribute("exception",e);
        return "login";
    }

//    @RequestMapping("/exLogin")
//    public String exLogin(@RequestParam String account,@RequestParam String password){
//        SysUser sysUser=sysUserService.login(account,password);
//        if (null==sysUser){
//            throw new RuntimeException("用户名或密码不正确");
//        }
//        return "redirect:/user/toMain";
//    }
}
